
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       fms_motors.c
  * @author     baiyang
  * @date       2021-8-22
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "fms.h"
#include "logger.h"

#include <string.h>

#include <uITC/uITC.h>
#include <uITC/uITC_msg.h>

#include <gcs_mavlink/gcs.h>
#include <srv_channel/srv_channel.h>
/*-----------------------------------macro------------------------------------*/
#define FMS_ARM_DELAY               20  // called at 10hz so 2 seconds
#define FMS_DISARM_DELAY            20  // called at 10hz so 2 seconds
#define FMS_AUTO_TRIM_DELAY         100 // called at 10hz so 10 seconds
#define FMS_LOST_VEHICLE_DELAY      10  // called at 10hz so 1 second
/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/

/*----------------------------------variable----------------------------------*/
static uint32_t auto_disarm_begin;
/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
// arm_motors_check - checks for pilot input to arm or disarm the copter
// called at 10hz
void fms_arm_motors_check()
{
    static int16_t arming_counter;

    mb_arming_t arming = mb_arming_get_singleton();

    // check if arming/disarm using rudder is allowed
    enum RudderArming arming_rudder = arming->_rudder_arming;
    if (arming_rudder == ARMING_RUDDER_IS_DISABLED) {
        return;
    }

    // ensure throttle is down
    if (fms.channel_throttle->control_in > 0) {
        arming_counter = 0;
        return;
    }

    int16_t yaw_in = fms.channel_yaw->control_in;

    // full right
    if (yaw_in > 4000) {

        // increase the arming counter to a maximum of 1 beyond the auto trim counter
        if (arming_counter <= FMS_AUTO_TRIM_DELAY) {
            arming_counter++;
        }

        // arm the motors and configure for flight
        if (arming_counter == FMS_ARM_DELAY && !fms.motors->_armed) {
            // reset arming counter if arming fail
            if (!mb_arming_arm(ARMING_METHOD_RUDDER, true)) {
                arming_counter = 0;
            }
        }

        // arm the motors and configure for flight
        if (arming_counter == FMS_AUTO_TRIM_DELAY && fms.motors->_armed && mode_number(fms.flightmode) == STABILIZE) {
            gcs_send_text(MAV_SEVERITY_INFO, "AutoTrim start");
            fms.auto_trim_counter = 250;
            fms.auto_trim_started = false;
            // ensure auto-disarm doesn't trigger immediately
            auto_disarm_begin = time_millis();
        }

    // full left and rudder disarming is enabled
    } else if ((yaw_in < -4000) && (arming_rudder == ARMING_RUDDER_ARMDISARM)) {
        if (!mode_has_manual_throttle(fms.flightmode) && !fms.ap.land_complete) {
            arming_counter = 0;
            return;
        }

        // increase the counter to a maximum of 1 beyond the disarm delay
        if (arming_counter <= FMS_DISARM_DELAY) {
            arming_counter++;
        }

        // disarm the motors
        if (arming_counter == FMS_DISARM_DELAY && fms.motors->_armed) {
            mb_arming_disarm(ARMING_METHOD_RUDDER, true);
        }

    // Yaw is centered so reset arming counter
    } else {
        arming_counter = 0;
    }
}

// auto_disarm_check - disarms the copter if it has been sitting on the ground in manual mode with throttle low for at least 15 seconds
void fms_auto_disarm_check()
{
    uint32_t tnow_ms = time_millis();
    uint32_t disarm_delay_ms = 1000*math_constrain_int16(fms.g.disarm_delay, 0, 127);

    // exit immediately if we are already disarmed, or if auto
    // disarming is disabled
    if (!fms.motors->_armed || disarm_delay_ms == 0 || mode_number(fms.flightmode) == THROW) {
        auto_disarm_begin = tnow_ms;
        return;
    }

    // if the rotor is still spinning, don't initiate auto disarm
    if (fms.motors->_spool_state > MB_MOTOR_GROUND_IDLE) {
        auto_disarm_begin = tnow_ms;
        return;
    }

    // always allow auto disarm if using interlock switch or motors are Emergency Stopped
    if ((fms.ap.using_interlock && !fms.motors->_interlock)) {
        // use a shorter delay if using throttle interlock switch or Emergency Stop, because it is less
        // obvious the copter is armed as the motors will not be spinning
        disarm_delay_ms /= 2;
    } else {
        bool sprung_throttle_stick = (fms.g.throttle_behavior & THR_BEHAVE_FEEDBACK_FROM_MID_STICK) != 0;
        bool thr_low;
        if (mode_has_manual_throttle(fms.flightmode) || !sprung_throttle_stick) {
            thr_low = fms.ap.throttle_zero;
        } else {
            float deadband_top = rc_get_control_mid(fms.channel_throttle) + fms.g.throttle_deadzone;
            thr_low = fms.channel_throttle->control_in <= deadband_top;
        }

        if (!thr_low || !fms.ap.land_complete) {
            // reset timer
            auto_disarm_begin = tnow_ms;
        }
    }

    // disarm once timer expires
    if ((tnow_ms-auto_disarm_begin) >= disarm_delay_ms) {
        mb_arming_disarm(ARMING_METHOD_DISARMDELAY, true);
        auto_disarm_begin = tnow_ms;
    }
}

// check for pilot stick input to trigger lost vehicle alarm
void fms_lost_vehicle_check()
{
    static uint8_t soundalarm_counter;

    // disable if aux switch is setup to vehicle alarm as the two could interfere
    if (rcs_find_channel_for_option(RC_AUX_LOST_VEHICLE_SOUND)) {
        return;
    }

    // ensure throttle is down, motors not armed, pitch and roll rc at max. Note: rc1=roll rc2=pitch
    if (fms.ap.throttle_zero && !fms.motors->_armed && (fms.channel_roll->control_in > 4000) && (fms.channel_pitch->control_in > 4000)) {
        if (soundalarm_counter >= FMS_LOST_VEHICLE_DELAY) {
            if (notify_flags.vehicle_lost == false) {
                notify_flags.vehicle_lost = true;
                gcs_send_text(MAV_SEVERITY_NOTICE,"Locate Copter alarm");
            }
        } else {
            soundalarm_counter++;
        }
    } else {
        soundalarm_counter = 0;
        if (notify_flags.vehicle_lost == true) {
            notify_flags.vehicle_lost = false;
        }
    }
}

// update estimated throttle required to hover (if necessary)
//  called at 100hz
void fms_update_throttle_hover()
{
    // if not armed or landed or on standby then exit
    if (!fms.motors->_armed || fms.ap.land_complete || fms.standby_active) {
        return;
    }

    // do not update in manual throttle modes or Drift
    if (mode_has_manual_throttle(fms.flightmode) || (mode_number(fms.flightmode) == DRIFT)) {
        return;
    }

    // do not update while climbing or descending
    if (!math_flt_zero(fms.pos_control->_vel_desired.z)) {
        return;
    }

    // get throttle output
    float throttle = mb_motors_get_throttle(fms.motors);

    // calc average throttle if we are in a level hover.  accounts for heli hover roll trim
    if (throttle > 0.0f && fabsf(fms.ahrs->velocity_cm.z) < 60 &&
        labs(fms.ahrs->roll_sensor_cd-0) < 500 && labs(fms.ahrs->pitch_sensor_cd) < 500) {
        // Can we set the time constant automatically
        mb_motors_update_throttle_hover(fms.motors, 0.01f);
    }
}

/**
  * @brief       电机混控输出函数
  * @param[in]     
  * @param[out]  
  * @retval      
  * @note        
  */
void fms_motors_output()
{
    uitc_actuator_controls actuator_controls;
    uitc_actuator_outputs  actuator_outputs;
    uitc_sensor_baro baro;

    DEFINE_TIMETAG(set_air_density_ratio, 100);
    if (time_check_tag(TIMETAG(set_air_density_ratio)) && (itc_copy_from_hub(ITC_ID(sensor_baro), &baro) == 0)) {
        mb_motors_set_air_density_ratio(fms.motors, baro.air_density_ratio);
    }

    // Update arming delay state
    if (fms.ap.in_arming_delay && (!fms.motors->_armed || time_millis()-fms.arm_time_ms > ARMING_DELAY_SEC*1.0e3f || mode_number(fms.flightmode) == THROW)) {
        fms.ap.in_arming_delay = false;
    }

    // output any servo channels
    srv_channels_calc_pwm();

    // cork now, so that all channel outputs happen at once
    srv_channels_cork();

    // update output on any aux channels, for manual passthru
    srv_channels_output_ch_all();

    // update motors interlock state
    bool interlock = mb_motors_armed(fms.motors) && !fms.ap.in_arming_delay && (!fms.ap.using_interlock || fms.ap.motor_interlock_switch) && !srv_channels_get_emergency_stop();
    if (!mb_motors_get_interlock(fms.motors) && interlock) {
        mb_motors_set_interlock(fms.motors, true);
        aplog_write_event(LOG_EVENT_MOTORS_INTERLOCK_ENABLED);
    } else if (mb_motors_get_interlock(fms.motors) && !interlock) {
        mb_motors_set_interlock(fms.motors, false);
        aplog_write_event(LOG_EVENT_MOTORS_INTERLOCK_DISABLED);
    }

    if (fms.ap.motor_test) {
        // check if we are performing the motor test
        fms_motor_test_output();
    } else {
        // send output signals to motors
        mode_output_to_motors(fms.flightmode);

        // 这个地方不能使用内存拷贝memcpy函数，否则在windows下会出问题,尚不清楚原因
        actuator_controls.timestamp_us = time_micros64();
        actuator_controls.throttle = mb_motors_get_throttle(fms.motors) * 100.0f;
        for (int8_t i = 0; i<MB_MOTORS_MAX_NUM_MOTORS; i++) {
            actuator_controls.control[i] = ((mb_motors_mc_t)fms.motors)->_actuator[i];
        }

        // 这个地方不能使用内存拷贝memcpy函数，否则在windows下会出问题,尚不清楚原因
        actuator_outputs.timestamp_us = time_micros64();
        for (int8_t i = 0; i<MB_MOTORS_MAX_NUM_MOTORS; i++) {
            actuator_outputs.output[i] = mb_motors_output_to_pwm(fms.motors, ((mb_motors_mc_t)fms.motors)->_actuator[i]);
        }
    }

    // push all channels
    srv_channels_push();

    itc_publish(ITC_ID(vehicle_actuator_controls), &actuator_controls);
    itc_publish(ITC_ID(vehicle_actuator_outputs), &actuator_outputs);
}

/*------------------------------------test------------------------------------*/


